<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;
use App\Http\Controllers\ArticleCategoryController;
use App\ArticleCategory;
use Illuminate\Support\Facades\Storage;

class ArticleController extends Controller
{
    public $cats;
    public function __construct()
    {
        $article_category_controller = new ArticleCategoryController();
        $this->cats = $article_category_controller->getList(ArticleCategory::orderBy('sort','asc')->get(), 0, 0);//所有分类列表
    }

    public function _list(Request $request){
        $cond = [];
        $search_data = [];
        if($request->filled('cat_id')){
            $cond[] = ['cat_id','=',$request->cat_id];
            $search_data['cat_id'] = $request->cat_id;
        }
        if($request->filled('sd')){
            $cond[] = ['article.created_at','>=',$request->sd.' 00:00:00'];
            $search_data['sd'] = $request->sd;
        }
        if($request->filled('ed')){
            $cond[] = ['article.created_at','<=',$request->ed.' 23:59:59'];
            $search_data['ed'] = $request->ed;
        }
        if($request->filled('title')){
            $cond[] = ['title','like','%'.$request->title.'%'];
            $search_data['title'] = $request->title;
        }
        $list = Article::where($cond)
            ->select(
                'article.id as id',
                'article.thumbnail as thumbnail',
                'article.title as title',
                'article_category.name as cat_name',
                'article.created_at as created_at'
            )
            ->leftJoin('article_category', 'article.cat_id', '=', 'article_category.id')
            ->orderBy('article.sort','asc')
            ->get();
        return view('Article.list',[
            'cats' => $this->cats,
            'list' => $list,
            'search_data' => $search_data
        ]);
    }

    public function edit(Request $request){
        $id = $request->filled('id') ? $request->id : null;
        $info = $id ? Article::find($id) : [];

        if(!$_POST){
            return view('Article.edit', [
                'cats' => $this->cats,
                'info' => $info
            ]);
        }

        $title = $request->filled('title') ? $request->title : '';
        $keywords = $request->filled('keywords') ? $request->keywords : '';
        $cat_id = $request->filled('cat_id') ? $request->cat_id : '';
        $content = $request->filled('content') ? parseUeditorImage($request['content']) : '';
        $thumbnail = $request->filled('thumbnail') ? $request['thumbnail'] : '';
        $sort = $request->filled('sort') ? $request['sort'] : 100;//默认100
        $author = $request->filled('author') ? $request['author'] : 'admin';

        if($id){
            //update
            Article::where('id', $id)->update([
                'title' => $title,
                'keywords' => $keywords,
                'cat_id' => $cat_id,
                'content' => $content,
                'thumbnail' => $thumbnail,
                'sort' => $sort,
                'author' => $author
            ]);
        }else{
            //add
            $article = new Article;
            $article->title = $title;
            $article->keywords = $keywords;
            $article->cat_id = $cat_id;
            $article->content = $content;
            $article->thumbnail = $thumbnail;
            $article->author = $author;
            $article->sort = $sort;
            $article->save();
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function del(Request $request){
        $id = $request->filled('id') ? $request->id : null;

        if(!$id)
            return json_encode([
                'code' => 0,
                'msg' => 'id can not be null'
            ]);

        $id_arr = explode(',', $id);
        foreach($id_arr as $v){
            //删除
            Article::destroy($v);
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function uploadImg(Request $request){
        if($request->hasFile('upload_thumbnail') && $request->file('upload_thumbnail')->isValid()){
            $img_url = QclouduUpload(md5(uniqid(md5(microtime(true)),true)), $request->file('upload_thumbnail')->getRealPath());
            return json_encode([
                'code' => 1,
                'msg' => 'success',
                'img_url' => $img_url
            ]);
//            $ext = $request->upload_thumbnail->extension();
//            $base_dir = '/picture/'.date('Ymd').'/';
//            $file_name = $this->randomKey(12).".".$ext;
//            $full_path = public_path() . $base_dir;
//
//            if (!file_exists($full_path)){
//                mkdir($full_path,0777,true);
//            }
//            file_put_contents(
//                $full_path . $file_name,
//                file_get_contents($request->file('upload_thumbnail')->getRealPath())
//            );
//            return json_encode([
//                'code' => 1,
//                'msg' => 'success',
//                'img_url' => $base_dir . $file_name
//            ]);
        }else{
            return json_encode([
                'code' => 0,
                'msg' => 'upload error,please try again'
            ]);
        }

    }

    public function randomKey($length){
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key = '';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,61)};    //生成php随机数
        }
        return $key;
    }

    //=====================================
    //          [API  Function]
    //=====================================

    public function info(Request $request){
        $id = $request->route('id');
        $info = Article::where('article.id',$id)
            ->select(
                'article.id as id',
                'article.thumbnail as thumbnail',
                'article.title as title',
                'article.keywords as keywords',
                'article.cat_id as cat_id',
                'article_category.name as cat_name',
                'article.created_at as created_at',
                'article.content as content',
                'article.author as author'
            )
            ->leftJoin('article_category', 'article.cat_id', '=', 'article_category.id')
            ->first();
        return json_encode([
            'code' => 1,
            'data' => $info
        ]);
    }

    public function getListByCat(Request $request){
        $cat_id = $request->route('cat_id');

        $list = Article::where('article.cat_id',$cat_id)
            ->select(
                'article.id as id',
                'article.thumbnail as thumbnail',
                'article.title as title',
                'article.keywords as keywords',
                'article.cat_id as cat_id',
                'article_category.name as cat_name',
                'article.created_at as created_at',
                //'article.content as content',
                'article.author as author'
            )
            ->leftJoin('article_category', 'article.cat_id', '=', 'article_category.id')
            ->orderBy('article.sort','asc')
            ->orderBy('article.created_at','desc')
            ->get();

        return json_encode([
            'code' => 1,
            'data' => $list
        ]);

    }
}
